/**
 *******************************************************************************
 * @FileName  : tlsr825x_systimer.c
 * @Author    : GaoQiu
 * @CreateDate: 2020-09-10
 * @Copyright : Copyright(C) GaoQiu
 *              All Rights Reserved.
 *
 *******************************************************************************
 *
 * The information contained herein is confidential and proprietary property of
 * GaoQiu and is available under the terms of Commercial License Agreement
 * between GaoQiu and the licensee in separate contract or the terms described
 * here-in.
 *
 * This heading MUST NOT be removed from this file.
 *
 * Licensees are granted free, non-transferable use of the information in this
 * file under Mutual Non-Disclosure Agreement. NO WARRENTY of ANY KIND is provided.
 *
 *******************************************************************************
 */
#include "tlsr825x.h"
#include "tlsr825x_systimer.h"

/**
 * @brief : Initialize system timer.
 *          !!Note: set counter to 0, set 32k tracking to 8000 and enable tracking.
 * @return: none.
 */
void SysTimer_Init(void)
{
	SYS_TIM->CTRL &= ~SYS_TIM_32K_TRACK_EN; //Disable 32k tracking.
	SYS_TIM->TRACKING = 8000;               //Set default 32k tracking value.
	SYS_TIM->CTRL |= SYS_TIM_32K_TRACK_EN;  //Enable 32k tracking.

	SYS_TIM->CTRL_STATE &= ~SYS_TIM_EN;     //Disable system timer.
	SYS_TIM->CNT = 0;                       //Set system timer conuter value.
}

/**
 * @brief : Set system timer counter Initialization value.
 * @param : value    counter value.
 * @return: none.
 */
void SysTimer_SetInitCounter(uint32_t value)
{
	uint8_t tmp = SYS_TIM->CTRL_STATE;
	SYS_TIM->CTRL_STATE &= ~SYS_TIM_EN;
	SYS_TIM->CNT = value;
	SYS_TIM->CTRL_STATE = tmp;
}

/**
 * @brief : delay us.
 *          !!! Note: only this API is usable after system timer is enabled.
 * @param : us     range of 1 - UINT32_MAX/SYS_TIM_TICK_PER_US
 * @return: none.
 */
RAM_CODE
void delay_us(uint32_t us)
{
	if(us > (UINT32_MAX >> 4)){
		us = (UINT32_MAX >> 4);
	}

	uint32_t nowTick = SysTimer_GetCurTick();
	while(!SysTimer_IsTimeExpired(nowTick, us));
}

/**
 * @brief : delay ms.
 *          !!! Note: only this API is usable after system timer is enabled.
 * @param : us     range of 1 - UINT32_MAX/SYS_TIM_TICK_PER_US/1000
 * @return: none.
 */
void delay_ms(uint32_t ms)
{
	delay_us(ms*1000);
}
